package com.wanxi.user.controller;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.lang.UUID;
import com.wanxi.common.result.ResultDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;


@RestController
public class CodeController {


    @Autowired
    private RedisTemplate<String,Object> redisTemplate;


    @RequestMapping(value = "/code")
    public ResultDTO getCode(HttpServletRequest req) {
        //创建图片
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(130, 45, 4, 100);
        //验证码字符的来源
        RandomGenerator randomGenerator = new RandomGenerator("0123456789abcdecghigklmzobqrstuvwsyz", 4);  //生成4个随机数
        //将验证码放到图片上
        lineCaptcha.setGenerator(randomGenerator);

        lineCaptcha.createCode();

        String code = lineCaptcha.getCode();  //获取生成的验证码

//        req.getSession().setAttribute("sCode", code);

        UUID uuid = UUID.randomUUID();

        redisTemplate.opsForValue().set("code" + uuid,code,30, TimeUnit.SECONDS);


        return ResultDTO.builder()
                .code(0)
                .msg("data:image/png;base64," + lineCaptcha.getImageBase64())
                .data("code" + uuid)
                .build();
//        resp.getWriter().println(JSONObject.toJSONString(ResultDto.getInstance("data:image/png;base64," + lineCaptcha.getImageBase64().toString())));
//        return ResultDto.getInstance("data:image/png;base64," + lineCaptcha.getImageBase64());
    }

}

